<?php

class Core_Agent_Component_Subject_Controller_Subject extends Dcmp_Component_Controller {

    public function createAction(){
        $category = App::getModel('subject/collection_category')->load();
        $themes = App::getModel('design/collection_page_theme')->filterBy('type','subject')->load();
//        $this->getPage()->getNavigation()->addLabel('创建主题');
        return $this->viewResult(array('category'=>$category,'themes'=>$themes));
    }

    public function editAction($id){
        $model = App::getModel('subject/content')->load($id);
        $this->getPage()->getNavigation()->addLabel('编辑主题')->addLabel($model->getName());
        return $this->createAction($model->getAreaId())->setModel($model);
    }

    public function savePostAction() {
        if ($this->saveModel('draft', $model)) {
            return $this->redirectResult($this->getUrl(array('subject_id'=>$this->getSession()->get('current_subject_id')),'index'));
        }
        return $this->createAction()->setModel($model);
    }

    public function previewAction($id){
        $this->getSession()->set('is_subject_preview','a');
        return $this->redirectResult('/subject/content/detail/id/'.$id);
    }

    private function saveModel($state, &$savedModel = NULL) {
        $data = $this->getRequest()->getForm('content');
        $model = App::getModel('subject/content');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }

        $model  ->addData($data)
                ->setStatus($state)
                ->setOwnerId($this->getIdentity()->getId());
        $savedModel = $model;
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            $this->getMessager()->addInform($this->__('share.message.success'));
            return TRUE;
        }
        else {
            $this->getMessager()->addError($errors);
            return FALSE;
        }
    }

    public function indexAction($sort = NULL){
        $this->getHistory()->record();
        Kd_Web::getPage()->setTitle('我的主题');
        $subjects = App::getModel('subject/collection_content')
                ->joinAccountRelation()
                ->joinCategory()
                ->filterBy('accountid',$this->getIdentity()->getId());
        if(!is_null($sort)){
            $subjects->sortBy($sort,'desc');
        }
        $subjects ->load();
        return $this->viewResult(array('subjects'=>$subjects));
    }

   
}